package org.dromara.system.pay;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.util.Md5Util;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 普通商户模式微信APP支付
 */
@Slf4j
@Service
public class WxPayService {

    /**
     * 微信APPID
     */
    public static String APP_ID = "wx55249cf4aa520aac";
    /**
     * 微信商户号
     */
    public static String MCHID = "1614300413";
    /**
     * 微信支付接口秘钥
     */
    public static String PARTNERKEY = "58f9e22163cb89eea8356ac42fc50b48";

    /**
     * 非证书模式支付
     * @param params 支付参数
     * @return
     */
    public SortedMap<Object, Object> creatOrder(Map<String, String> params) {
        SortedMap<Object, Object> signParam = new TreeMap<>();
        try {
            int price = (new BigDecimal(params.get("amount"))).multiply(new BigDecimal("100")).setScale(0, 6).intValue();
            String strTime = getWxTimeStamp();
            SortedMap<Object, Object> packageParams = new TreeMap<>();
            packageParams.put("appid", APP_ID);
            packageParams.put("mch_id", MCHID);
            packageParams.put("nonce_str", strTime);
            packageParams.put("sign_type", "MD5");
            packageParams.put("spbill_create_ip", "127.0.0.1");
            packageParams.put("body", params.get("body"));
            packageParams.put("out_trade_no", params.get("tradeNo"));
            packageParams.put("total_fee", String.valueOf(price));
            packageParams.put("notify_url", params.get("notifyUrl"));
            packageParams.put("trade_type", "APP");
            String sign = getSign("UTF-8", packageParams, PARTNERKEY);
            packageParams.put("sign", sign);
            String requestXML = getRequestXml(packageParams);
            log.info("统一下单参数：{}" + requestXML);
            String resXml = postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
            Map<String, String> map = doXMLParse(resXml);
            log.info("统一下单返回：{}" + map);
            if ("FAIL".equals(map.get("return_code"))) {
                return null;
            }
            signParam.put("appid", APP_ID);
            signParam.put("partnerid", MCHID);
            signParam.put("prepayid", map.get("prepay_id"));
            signParam.put("package", "Sign=WXPay");
            signParam.put("noncestr", strTime);
            signParam.put("timestamp", strTime);
            String signTwo = getSign("UTF-8", signParam, PARTNERKEY);
            signParam.put("sign", signTwo);
            return signParam;
        } catch (Exception e) {
            log.info("微信支付异常:{}" + e.getMessage());
            return null;
        }
    }

    public static String getSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<Object, Object>> es = packageParams.entrySet();
        Iterator<Map.Entry<Object, Object>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k))
                sb.append(k + "=" + v + "&");
        }
        sb.append("key=" + API_KEY);
        System.out.println("签名" + sb.toString());
        return Md5Util.md5Hex(sb.toString()).toUpperCase();
    }

    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set<Map.Entry<Object, Object>> es = parameters.entrySet();
        Iterator<Map.Entry<Object, Object>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign"
                .equalsIgnoreCase(k)) {
                sb.append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                continue;
            }
            sb.append("<" + k + ">" + v + "</" + k + ">");
        }
        sb.append("</xml>");
        return sb.toString();
    }

    public static String postData(String urlStr, String data) {
        int CONNECT_TIMEOUT = 5000;
        String DEFAULT_ENCODING = "UTF-8";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if (data == null)
                data = "";
            writer.write(data);
            writer.flush();
            writer.close();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException iOException) {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException iOException1) {
            }
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException iOException) {
            }
        }
        return null;
    }

    public Map<String, String> doXMLParse(String strxml) throws IOException, JDOMException {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if (null == strxml || "".equals(strxml)) {
            return null;
        }
        Map<String, String> m = new HashMap<>();
        InputStream in = new ByteArrayInputStream(strxml.getBytes(StandardCharsets.UTF_8));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator<Element> it = list.iterator();
        while (it.hasNext()) {
            Element e = it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }
        in.close();
        return m;
    }

    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                Element e = it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty())
                    sb.append(getChildrenText(list));
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }

    public void sendToCFT(String msg, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            String strHtml = msg;
            out = response.getWriter();
            out.println(strHtml);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

    public static String getWxTimeStamp() {
        long time = (new Date()).getTime() / 1000L;
        return String.valueOf(time);
    }
}

